package org.qiandaosystem.qiandaosystemsource.service;

import org.qiandaosystem.qiandaosystemsource.dto.ExportSignStatusDto;
import org.qiandaosystem.qiandaosystemsource.entity.Student;
import org.qiandaosystem.qiandaosystemsource.entity.SignRecord;
import org.qiandaosystem.qiandaosystemsource.repository.StudentRepository;
import org.qiandaosystem.qiandaosystemsource.repository.SignRecordRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SignRecordService {

    @Autowired
    private SignRecordRepository signRecordRepository;

    @Autowired
    private StudentRepository studentRepository;

    public List<ExportSignStatusDto> getSignStatusByActivityId(Integer activityId) {
        List<SignRecord> signRecords = signRecordRepository.findByActivityId(activityId);

        // 获取所有相关的学生ID
        List<Integer> studentIds = signRecords.stream()
                .map(SignRecord::getStudentId)
                .distinct()
                .collect(Collectors.toList());

        // 查询所有相关的学生信息
        List<Student> students = studentRepository.findByIdIn(studentIds);

        // 构建导出 DTO 列表
        List<ExportSignStatusDto> exportDtos = new ArrayList<>();
        for (Student student : students) {
            // 根据学生ID获取该学生的签到记录
            SignRecord signRecord = signRecords.stream()
                    .filter(sr -> sr.getStudentId().equals(student.getId()))
                    .findFirst()
                    .orElse(null);

            ExportSignStatusDto dto = new ExportSignStatusDto();
            dto.setStudentName(student.getRealName());

            // 设置签到状态
            if (signRecord != null) {
                dto.setStatus(signRecord.getStatus().toString());
            } else {
                dto.setStatus("未签到");
            }

            exportDtos.add(dto);
        }

        return exportDtos;
    }
}